package com.demo.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.Optional;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池
 */
@Configuration
public class ThreadPoolTaskExecutorConfig implements AsyncConfigurer {

	// 当前机器核数
	public static final int cpuNum = Runtime.getRuntime().availableProcessors();

	@Value("${thread.corePoolSize}")
	private Integer corePoolSize;

	@Value("${thread.maxPoolSize}")
	private Integer maxPoolSize;

	@Value("${thread.queueCapacity}")
	private Integer queueCapacity;

	@Value("${thread.keepAlive}")
	private Integer keepAlive;

	@Value("${thread.awaitTerminationSeconds}")
	private Integer awaitTerminationSeconds;

	@Override
	@Bean
	public Executor getAsyncExecutor() {

		ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
		// 核心线程池数
		threadPoolTaskExecutor.setCorePoolSize(optionl(corePoolSize, cpuNum));
		// 最大线程池数
		threadPoolTaskExecutor.setMaxPoolSize(optionl(maxPoolSize, cpuNum * 2));
		// 任务队列的容量
		threadPoolTaskExecutor.setQueueCapacity(optionl(queueCapacity, 3));
		// 非核心线程的存活时间
		threadPoolTaskExecutor.setKeepAliveSeconds(optionl(keepAlive, 10));
		threadPoolTaskExecutor.setThreadNamePrefix("test-thread-");
		threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
		threadPoolTaskExecutor.initialize();
		// 创建线程的等待时间
		threadPoolTaskExecutor.setAwaitTerminationSeconds(optionl(awaitTerminationSeconds, 10));
		return threadPoolTaskExecutor;
	}

	/**
	 * 判空-替换
	 * @param key 原值
	 * @param key2 替换值
	 * @return 结果
	 */
	public Integer optionl(Integer key, Integer key2) {
		// 如果key为空则赋值为key2
		return Optional.ofNullable(key).orElse(key2);
	}

}
